package com.example.partition;

import com.example.model.WaterSensor;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.functions.Partitioner;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;

/**
 * Created with IntelliJ IDEA.
 * ClassName: Paratitioning
 * Package: com.example.partition
 * Description:
 * User: fzykd
 *
 * @Author: LQH
 * Date: 2023-07-22
 * Time: 19:42
 */

//物理分区算子 随机分区  轮询算子 缩放算子 广播算子
public class Partitioning {
    public static void main(String[] args) throws Exception {

        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        env.setParallelism(2);

        SingleOutputStreamOperator<WaterSensor> mapData = env.socketTextStream("hadoop102", 7777)
                .map(new MapFunction<String, WaterSensor>() {
                    @Override
                    public WaterSensor map(String value) throws Exception {
                        final String[] s = value.split(" ");

                        return new WaterSensor(s[0], Long.valueOf(s[1]), Integer.valueOf(s[2]));
                    }
                });

        //随机分区 shuffle 随机打乱 均匀传递
        ///mapData.shuffle().print();

        //轮询分期 依次按顺序发牌
        //rebalance()

        //rescale 缩放分区
        //只给自己团队内的所有人轮流发牌

        //广播 broadcast
        //下游的所有子任务都可以收到信息

        //global 全局分区
        //会将数据都发往第一个并行子任务中去


        //自定义分区算子

        final DataStream<WaterSensor> custom =
                //PartitionCustom 自定义分区
                mapData.partitionCustom(new Partitioner<String>() {
                                            //参数1：分区器 自定义分区策略
                                            @Override
                                            public int partition(String key, int numPartitions) {
                                                //numPartitions 是设置的分区数
                                                //和 setParallelism(2) 一致
                                                System.out.println(numPartitions);

                                                return Integer.parseInt(key) % numPartitions;
                                            }
                                        },
                        //参数2：Key的选择器 从数据对象中 提取出分区对象 传给分区器
                        new KeySelector<WaterSensor, String>() {
                            @Override
                            public String getKey(WaterSensor value) throws Exception {
                                //根据ID分区
                                return value.getId();
                            }
                        });


        custom.print();

        env.execute();


    }
}
